package com.yupi.xupicturebackend.aop;

import com.yupi.xupicturebackend.annotation.AuthCheck;
import com.yupi.xupicturebackend.exception.BusinessException;
import com.yupi.xupicturebackend.exception.ErrorCode;
import com.yupi.xupicturebackend.model.entity.User;
import com.yupi.xupicturebackend.model.enums.UserRoleEnum;
import com.yupi.xupicturebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 21829
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;


    @Around("@annotation(authCheck)")
    public Object doIntercept(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //1.获取请求某个资源所需要的权限
        String mustRole = authCheck.mustRole();
        //2.通过全局上下文对象拿到用户请求对象
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //3.通过用户请求对象拿到当前登录用户
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum mustRoleEnum = UserRoleEnum.getUserRoleEnum(mustRole);
        //4.如果不需要权限放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        //5.如果执行到这说明这个资源需要用户拥有某个权限才可以放行
        // 获取到用户权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getUserRoleEnum(loginUser.getUserRole());
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //6.要求拥有管理员权限，但用户没有管理员权限 拒绝
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return joinPoint.proceed();
    }
}
